package com.tth.learn.addproperties.com.tth.learn.java2;

import com.tth.learn.addproperties.java1.Person;
import org.junit.Test;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;

/**
 * 获取运行时类的方法结构
 * @Author tth
 * @Date 2022/12/29 16:54
 */
public class MethodsTest {

    @Test
    public void test1() {
        Class<Person> clazz = Person.class;
        // getMethods()：获取当前运行时类及其父类中public修饰的方法
        Method[] methods = clazz.getMethods();
        for (Method m: methods) {
            System.out.println(m);
        }

        System.out.println("********************");

        // getDeclaredMethods()：获取当前运行时类中声明的所有方法，不包含父类中的方法
        Method[] declaredMethods = clazz.getDeclaredMethods();
        for (Method m: declaredMethods) {
            System.out.println(m);
        }
    }

    @Test
    public void test2() {
        Class<Person> clazz = Person.class;
        Method[] declaredMethods = clazz.getDeclaredMethods();

        for (Method m: declaredMethods) {
            // 获取方法声明的注解
            Annotation[] annotations = m.getAnnotations();
            for (Annotation a: annotations) {
                System.out.print(a + "\t");
            }

            // 获取方法的权限修饰符
            int modifiers = m.getModifiers();
            System.out.print(Modifier.toString(modifiers)+ "\t");

            // 获取方法的返回值类型
            Class<?> returnType = m.getReturnType();
            System.out.print(returnType + "\t");

            // 获取方法名
            String name = m.getName();
            System.out.print(name);
            System.out.print("(");

            // 获取形参列表
            Class<?>[] parameterTypes = m.getParameterTypes();
            if (parameterTypes != null && parameterTypes.length != 0) {
                for (int i = 0; i < parameterTypes.length; i++) {
                    if (i == parameterTypes.length - 1) {
                        System.out.print(parameterTypes[i].getName() + "args_" + i);
                    }else {
                        System.out.print(parameterTypes[i].getName() + "args_" + i + ",");
                    }
                }
            }
            System.out.print(")");

            // 获取方法抛出的异常
            Class<?>[] exceptionTypes = m.getExceptionTypes();
            if (exceptionTypes != null && exceptionTypes.length != 0) {
                System.out.print(" throws ");
                for (int i = 0; i < exceptionTypes.length; i++) {
                    if (i == exceptionTypes.length - 1) {
                        System.out.print(exceptionTypes[i].getName());
                    }else {
                        System.out.print(exceptionTypes[i].getName() + ", ");
                    }
                }
            }
            System.out.println();
        }
    }
}
